//
//  XQButton.m
//  JoinPeso
//
//  Created by 小琦 on 2024/11/22.
//

#import "XQButton.h"

@interface XQButton()
@property (nonatomic,strong) UIButton *button;
@property (nonatomic,copy) NSString *buttonTitle;
@property (nonatomic,strong) UIColor *buttonBackgroundColor;
@end

@implementation XQButton

- (instancetype)initWithTitle:(NSString *)title {
    return [self initWithTitle:title bgColor:[UIColor blueColor]];
}

- (instancetype)initWithTitle:(NSString *)title bgColor:(UIColor *)color {
    self = [super init];
    if (self) {
        _buttonTitle = title;
        _buttonBackgroundColor= color;
        [self makeUI];
        [self makeConstraints];
    }
    return self;
}

- (void)makeUI {
    [self addSubview:self.button];
}

- (void)makeConstraints {
    [self.button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@0);
        make.left.equalTo(@12);
        make.right.equalTo(@-12);
        make.height.mas_equalTo(45);
        make.bottom.equalTo(@0);
    }];
}

#pragma mark - setter

- (void)setTitle:(NSString *)title {
    [self.button setTitle:title forState:UIControlStateNormal];
}

- (void)setBgColor:(UIColor *)bgColor {
    [_button setBackgroundImage:[UIImage imageWithColor:bgColor] forState:UIControlStateNormal];
    [_button setBackgroundImage:[UIImage imageWithColor:[bgColor colorWithAlphaComponent:0.5]] forState:UIControlStateDisabled];
}

- (void)setEnabled:(BOOL)enabled {
    if (enabled) {
        [self.button setBackgroundImage:[UIImage imageWithColor:self.buttonBackgroundColor] forState:UIControlStateNormal];
    }else {
        [self.button setBackgroundImage:[UIImage imageWithColor:[self.buttonBackgroundColor colorWithAlphaComponent:0.5]] forState:UIControlStateNormal];
    }
}

#pragma mark - private

- (void)buttonClick {
    if (self.onTapHandle) {
        self.onTapHandle();
    }
}

#pragma mark - lazy

- (UIButton *)button {
    if (!_button) {
        _button = [UIButton buttonWithType:UIButtonTypeCustom];
        _button.titleLabel.font = [UIFont boldSystemFontOfSize:20];
        _button.layer.cornerRadius = 22.5;
        _button.layer.masksToBounds = YES;
        [_button setTitle:self.buttonTitle forState:UIControlStateNormal];
        [_button setBackgroundImage:[UIImage imageWithColor:self.buttonBackgroundColor] forState:UIControlStateNormal];
        [_button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_button addTarget:self action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _button;
}

@end
